const express = require('express')
const path = require('path')
const app = express()
// app.all('*', function(req, res, next) {
//     // res.header("Access-Control-Allow-Origin", "*");
//     next();
// });
//静态资源目录
app.use(express.static(path.join(__dirname, 'public')));
let port = 3003
app.get('/home', (req, res, next) => {
    res.writeHead(200, { 'Content-type': 'text/html;charset=utf-8' })
    res.end('欢迎来到express')
    next()
})

const server = app.listen(port, () => { console.log('成功启动express服务,端口号是' + port) })
//引入socket.io传入服务器对象 让socket.io注入到web网页服务
let roomObj = {}
const io = require('socket.io')(server);
io.on('connect', (websocketObj) => {  //connect 固定的  
    //房间的roomId唯一标识
    let roomId = '';
    // 监听事件 
    websocketObj.on('roomID', (roomID) => {
        roomObj[roomID] ? ++roomObj[roomID] : roomObj[roomID] = 1
        roomId = roomID
        //超过两人 返回人员满  只能观战
        if (roomObj[roomID] > 2) {
            // roomObj[roomID] = 2
            websocketObj.emit('webEvent', '房间号' + roomId + "人员已满，只能观战")
        }
        websocketObj.join(roomID)
        console.log("有人加入" + roomId + "房间===目前有" + roomObj[roomID] + "人");
        console.log('当前房间号有===', roomObj);
        io.to(roomId).emit('webEvent', '恭喜链接websocket服务成功：目前链接的地址为：http://127.0.0.1:3000,房间号为' + roomId)
    })
    let itemsArr = []
    //加入房间后，打印出socket和room的信息
    //链接成功后立即触发webEvent事件
    websocketObj.on('sendItemsArr', (sendItemsArr) => {
        itemsArr = sendItemsArr
        //触发所以的 sendFunEventCallBack 事件  让前端监听
        // io.sockets.emit("getItemsArr", itemsArr);
        io.to(roomId).emit("getItemsArr", itemsArr);
    })
    websocketObj.on('clearItemsArr', () => {
        let clearItemsArr = JSON.parse(itemsArr)
        clearItemsArr.lineXAndlineYArrRed = []
        clearItemsArr.lineXAndlineYArrBlack = []
        clearItemsArr.hasChessmanArrList = []
        clearItemsArr.blackOrRedChessman = 0
        //触发所以的 sendFunEventCallBack 事件  让前端监听
        io.to(roomId).emit("clearItemsArrAll", JSON.stringify(clearItemsArr));
    })
})
